package com.bcx.crm.mybatis.core;

import com.bcx.crm.entity.Template;
import com.bcx.crm.mapper.templateTestMapper.SelectTemplateMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ys on 2018/3/17.
 */
public class SqlSessionFactoryUtil {
    public static void main(String[] args) throws IOException {
        getSqlSessionFactory();
    }
    public static void getSqlSessionFactory() throws IOException {
        //1.生成 sqlSessionFactory
        String resource = "com/bcx/crm/mybatis/core/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = null;
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.标准sqlSession使用方法
            //定义SqlSession
            SqlSession sqlSession = null;
            try{
                //打开sqlSession会话
                sqlSession = sqlSessionFactory.openSession();
                SelectTemplateMapper selectTemplateMapper = sqlSession.getMapper(SelectTemplateMapper.class);
                List<Template> list = selectTemplateMapper.getList1(getMap());
                System.out.println("size="+list.size());
                sqlSession.commit();
            }catch (Exception ex){
                System.err.println(ex.getMessage());
                if (null != sqlSession){
                    sqlSession.rollback();
                }
            }finally {
                //在finally语句中确保资源被顺利关闭
                if (null != sqlSession){
                    sqlSession.close();
                }
            }
        }catch (Exception ex){
            System.err.println(ex.getMessage());
        }

    }
    public static Map<String,Object> getMap(){
        List<String> list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        list.add("0865372c-9e50-47bb-b28a-87a9cbdd");
        list.add("0f4c1261-177c-4f1a-94fa-0db96537");
        list.add("10674c05-8368-4f58-a91a-33bb20c2");
        map.put("row_id",list);
        map.put("template_code","0");
        return map;
    }
}
